﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using YueRu.Common.Encrypt;

namespace YueRu.Common
{
    /// <summary>
    /// 生成请求时签名
    /// </summary>
    public sealed class RequestSignHelper
    {
        /// <summary>
        /// 生成请求时签名
        /// </summary>
        /// <param name="sPara"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string BuildRequestMysign(SortedDictionary<string, string> sPara, string key)
        {
            //把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
            var prestr = CreateLinkString(sPara);
            //把最终的字符串签名，获得签名结果
            var mysign = YueRuMd5.Sign(prestr, key);
            
            return mysign;
        }

        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
        /// </summary>
        /// <param name="dicArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        public static string CreateLinkString(SortedDictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + temp.Value + "&");
            }

            //去掉最後一個&字符
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

        /// <summary>
        /// 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对参数值做urlencode
        /// </summary>
        /// <param name="dicArray">需要拼接的数组</param>
        /// <returns>拼接完成以后的字符串</returns>
        public static string CreateLinkStringUrlencode(SortedDictionary<string, string> dicArray)
        {
            var prestr = new StringBuilder();
            foreach (var temp in dicArray)
            {
                prestr.Append(temp.Key + "=" + HttpUtility.UrlEncode(temp.Value) + "&");
            }

            //去掉最後一個&字符
            var nLen = prestr.Length;
            prestr.Remove(nLen - 1, 1);

            return prestr.ToString();
        }

    }
}